﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XF.Common;
using XF.Meeting.Entity.CommonEntity;
using XF.Meeting.Entity.CommonEntity.wx;
using XF.Meeting.Entity.Enum;
using XF.Meeting.Entity.View;
using XF.Meeting.IDal;
using XF.Sugar.IService;
namespace XF.Meeting.Service
{
    public class BPMService : BaseService, IBPMService
    {
        private UEntity.LogEntity.ELogRecordEntity LogEntity = new UEntity.LogEntity.ELogRecordEntity();
        IBPMDal dal = null;
        public BPMService(string Operator, string OperaIP)
        {
            this.Operator = Operator;
            this.OperaIP = OperaIP;
            if (dal == null)
            {
                lock (this.OperaIP)
                {
                    if (dal == null)
                    {
                        dal = DalFactory.DalFactory.GetBPMDal();
                    }
                }
            }
        }
        public Task<string> ApproveClose(string strBTID, string strBOID, int iProcInstID, string eProcessInstanceResult, string strComment, DateTime dtTime)
        {
            LogEntity.Module = "XF.Meeting.Service.BPMService.ApproveClose";
            LogEntity.OperateObject = "ApproveClose";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = strBTID + "--" + strBOID + "--" + iProcInstID + "--" + eProcessInstanceResult + "--" + strComment + "--" + dtTime;
            int meetState = 1;
            int summaryState = 2;
            try
            {
                switch (eProcessInstanceResult)
                {
                    case "1":
                        meetState = (int)MeetingEnum.order;
                        summaryState = (int)SummaryEnum.end;
                        break;
                    case "0":
                        meetState = (int)MeetingEnum.nopass;
                        summaryState = (int)SummaryEnum.nopass;
                        break;
                    case "2":
                        meetState = (int)MeetingEnum.nullify;
                        summaryState = (int)SummaryEnum.nullify;
                        break;
                    default:
                        break;
                }
                var result = dal.ApproveClose(strBTID, strBOID, iProcInstID, eProcessInstanceResult, strComment, dtTime, meetState, summaryState);
                if (result.Result)
                {

                    RecordLog();
                    return Task.FromResult("<success>成功</success>");
                }
                else
                {
                    LogEntity.OperateResult = "Fail";
                    RecordLog();
                    return Task.FromResult("<error>失败</error>");
                }
            }
            catch (Exception ex)
            {
                LogEntity.OperateResult = "Fail";
                LogEntity.ErrorDescription = string.Format("ApproveClose Exception:{0}", ex.ToString());
                RecordLog();
                return Task.FromResult("<error>失败</error>");
            }

        }

        public Task<string> Audit(string strBTID, string strBOID, int iProcInstID, string strStepName, string strApproverId, string eAction, string strComment, DateTime dtTime)
        {
            LogEntity.Module = "XF.Meeting.Service.BPMService.Audit";
            LogEntity.OperateObject = "Audit";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = strBTID + "--" + strBOID + "--" + iProcInstID + "--" + strStepName + "--" + strApproverId + "--" + eAction + "==" + strComment + "--" + dtTime;
            int meetState = 1;
            int summaryState = 2;
            try
            {
                switch (eAction)
                {
                    //case "1":
                    //    meetState = (int)MeetingEnum.order;
                    //    summaryState = (int)SummaryEnum.end;
                    //    break;
                    case "2":
                        meetState = (int)MeetingEnum.nopass;
                        summaryState = (int)SummaryEnum.nopass;
                        break;
                }

                var result = dal.Audit(strBTID, strBOID, iProcInstID, strStepName, strApproverId, eAction, strComment, dtTime, meetState, summaryState);
                if (result.Result)
                {

                    RecordLog();
                    return Task.FromResult("<success>成功</success>");
                }
                else
                {
                    LogEntity.OperateResult = "Fail";
                    RecordLog();
                    return Task.FromResult("<error>失败</error>");
                }
            }
            catch (Exception ex)
            {
                LogEntity.OperateResult = "Fail";
                LogEntity.ErrorDescription = string.Format("Audit Exception:{0}", ex.ToString());
                RecordLog();
                return Task.FromResult("<error>失败</error>");
            }
        }

        public Task<string> CreateResult(string strBTID, string strBOID, int iProcInstID, string bSuccess, string procURL, string strMessage)
        {
            LogEntity.Module = "XF.Meeting.Service.BPMService.CreateResult";
            LogEntity.OperateObject = "CreateResult";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = strBTID + "--" + strBOID + "--" + iProcInstID + "--" + bSuccess + "--" + procURL + "--" + strMessage;
            try
            {
                var result = dal.CreateResult(strBTID, strBOID, iProcInstID, bSuccess, procURL, strMessage);

                if (result.Result)
                {
                    RecordLog();
                    return Task.FromResult("<success>成功</success>");
                }
                else
                {
                    LogEntity.OperateResult = "Fail";
                    RecordLog();
                    return Task.FromResult("<error>失败</error>");
                }
            }
            catch (Exception ex)
            {
                LogEntity.OperateResult = "Fail";
                LogEntity.ErrorDescription = string.Format("CreateResult Exception:{0}", ex.ToString());
                RecordLog();
                return Task.FromResult("<error>失败</error>");
            }
        }

        public Task<string> DoInvalid(string bsid, string btid, string boid, string procInstID, string userid, string invalidComment)
        {
            LogEntity.Module = "XF.Meeting.Service.BPMService.DoInvalid";
            LogEntity.OperateObject = "DoInvalid";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = bsid + "--" + btid + "--" + boid + "--" + procInstID + "--" + userid + "--" + invalidComment;
            try
            {
                var result = dal.DoInvalid(bsid, btid, boid, procInstID, userid, invalidComment);
                if (result.Result)
                {
                    RecordLog();
                    return Task.FromResult("<success>成功</success>");
                }
                else
                {
                    LogEntity.OperateResult = "Fail";

                    RecordLog();
                    return Task.FromResult("<error>失败</error>");
                }
            }
            catch (Exception ex)
            {
                LogEntity.OperateResult = "Fail";
                LogEntity.ErrorDescription = string.Format("DoInvalid Exception:{0}", ex.ToString());
                RecordLog();
                return Task.FromResult("<error>失败</error>");
            }
        }
        /// <summary>
        /// 获取会议信息或纪要信息
        /// </summary>
        /// <param name="CInfoId">会议id或者纪要id</param>
        /// <param name="type">1 会议 2纪要</param>
        /// <returns></returns>
        public async Task<BPMConfig> GetBPMCONFIG(int CInfoId, int type)
        {
            var result = await dal.GetBPMCONFIG(CInfoId, type, out string s);


            if (s == "")
            {
                BPMConfig bPM = TableToList.ToList<BPMConfig>(result.Tables[0]).FirstOrDefault();



                var data = TableToList.ToList<ProcessXmlData>(result.Tables[1]).FirstOrDefault();
                TimeSpan A = data.EndTime - data.BeginTime;
                var da = new DATA()
                {
                    title = data.title,
                    MtApprove = data.MtApprove,
                    MtDuration = A.TotalMinutes.ToString(),
                    MtLeader = data.MtLeader,
                    MtReporter = data.MtReporter,
                    MtSubject = data.MtSubject,
                    MtTime = data.BeginTime.ToString("g") + "--" + data.EndTime.ToString("g"),
                    RoomName = data.RoomName,
                    procInstID = data.procInstID,
                    Guid=data.Guid
                };

                if (type == 1)
                {
                    var res = dal.GetCInfoByID(CInfoId).Result;
                    var list = TableToList.ToList<MeetingInfoSingle>(res).FirstOrDefault();
                    bPM.ProcessData = da;
                    var men = TableToList.ToList<PersonInfo>(result.Tables[2]);
                    if (men != null && men.Count > 0)
                    {
                        var str = "";
                        foreach (var item in men)
                        {
                            str += item.AccountName + ",";
                        }
                        bPM.ProcessData.MtParticipant = str.Remove(str.Length - 1, 1);
                    }
                    if (string.IsNullOrWhiteSpace(list.CRoomIDs))
                    {
                        bPM.ProcessData.RoomName = list.CRoom;
                    }
                    else
                    {
                        bPM.ProcessData.RoomName = list.CRoom + "," + list.CRooms;
                    }
                }
                else
                {
                    var res = dal.GetCInfoByMinutesID(CInfoId).Result;
                    var list = TableToList.ToList<MeetingInfoSingle>(res).FirstOrDefault();
                    bPM.SummaryData = da;
                    var men = TableToList.ToList<PersonInfo>(result.Tables[2]);



                    if (men != null && men.Count > 0)
                    {
                        var str = "";
                        foreach (var item in men)
                        {
                            str += item.AccountName + ",";
                        }

                        bPM.SummaryData.MtParticipant = str.Remove(str.Length - 1, 1);
                    }
                    bPM.SummaryData.MtAttachment = TableToList.ToList<MtAttachment>(result.Tables[3]);
                    if (string.IsNullOrWhiteSpace(bPM.SummaryData.RoomName))
                    {
                        if (string.IsNullOrWhiteSpace(list.CRoomIDs))
                        {
                            bPM.SummaryData.RoomName = list.CRoom;
                        }
                        else
                        {
                            bPM.SummaryData.RoomName = list.CRoom + "," + list.CRooms;
                        }
                    }

                }

                return bPM;
            }
            else
            {
                return new BPMConfig();
            }


        }
        public async Task<WxConfig> GetWXCONFIG()
        {
            LogEntity.Module = "XF.Meeting.Service.BPMService.GetWXCONFIG";
            LogEntity.OperateObject = "GetWXCONFIG";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = "";
            try
            {
                
                var result = await dal.GetWXCONFIG(out string s);
                var config = TableToList.ToList<WxConfig>(result).FirstOrDefault();
                RecordLog();
                return config;
            }
            catch (Exception ex)
            {
                LogEntity.OperateResult = "Fail";
                LogEntity.ErrorDescription = string.Format("GetWXCONFIG Exception:{0}", ex.ToString());
                RecordLog();
                return null;
            }
        }

        public Task<string> UpdateBusinessData(string strBTID, string strBOID, int iProcInstID, string strStepName, string strApproverId, string strXML, DateTime dtTime)
        {
            LogEntity.Module = "XF.Meeting.Service.BPMService.UpdateBusinessData";
            LogEntity.OperateObject = "UpdateBusinessData";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = strBTID + "--" + strBOID + "--" + iProcInstID + "--" + strStepName + "--" + strApproverId + "--" + strXML + "==" + dtTime;
            try
            {
                var result = dal.UpdateBusinessData(strBTID, strBOID, iProcInstID, strStepName, strApproverId, strXML, dtTime);
                if (result.Result)
                {
                    RecordLog();
                }
                else
                {
                    LogEntity.OperateResult = "Fail";

                    RecordLog();
                }
                throw new NotImplementedException();
            }
            catch (Exception ex)
            {
                LogEntity.OperateResult = "Fail";
                LogEntity.ErrorDescription = string.Format("UpdateBusinessData Exception:{0}", ex.ToString());
                RecordLog();
                throw new NotImplementedException();
            }
        }

        public Task<bool> WriteBusinessDataToBPM(string bsid, string btid, string boid, string bsxml, string procInstID, string userid, string processUrl, int proType, int Id)
        {
            LogEntity.Module = "XF.Meeting.Service.BPMService.WriteBusinessDataToBPM";
            LogEntity.OperateObject = "WriteBusinessDataToBPM";
            LogEntity.OperateResult = "Success";
            LogEntity.OperationDescription = bsid + "--" + btid + "--" + boid + "--" + bsxml + "--" + procInstID + "--" + userid + "==" + processUrl + "--" + proType + "--" + Id;

            try
            {
                var result = dal.WriteBusinessDataToBPM(bsid, btid, boid, bsxml, procInstID, userid, processUrl, proType, Id);
                if (result.Result)
                {
                    RecordLog();
                }
                else
                {
                    LogEntity.OperateResult = "Fail";

                    RecordLog();
                }

                return result;
            }
            catch (Exception ex)
            {
                LogEntity.OperateResult = "Fail";
                LogEntity.ErrorDescription = string.Format("WriteBusinessDataToBPM Exception:{0}", ex.ToString());
                RecordLog();
                return Task.FromResult(false);
            }
        }
        private void RecordLog()
        {
            LogEntity.Operator = Operator;
            LogEntity.OperateIP = OperaIP;
            ULogWork.CLogToDataBase.RecordOperateLog(LogEntity);
        }
    }
}

